<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试成绩提交系统</title>
    <!-- 引入 Bootstrap CSS -->
    <link href="/cssAndjs/bootstrap.min.css" rel="stylesheet">
    <!-- 引入 Font Awesome -->
    <link href="/cssAndjs/font-awesome.min.css" rel="stylesheet">
    <!-- 引入 jQuery -->
    <script src="/cssAndjs/jquery.min.js"></script>
    <!-- 引入 Bootstrap JS -->
    <script src="/cssAndjs/bootstrap.bundle.min.js"></script>

    <style>
        body {
            background-color: #f8f9fa;
            padding: 20px;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
        }

        .card {
            margin-top: 20px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }

        .card-header {
            background-color: #0d6efd;
            color: white;
            font-weight: bold;
        }

        .table {
            margin-bottom: 0;
        }

        .table th {
            background-color: #f8f9fa;
            text-align: center;
        }

        .table td {
            vertical-align: middle;
        }

        .score-input {
            width: 80px;
            text-align: center;
        }

        .btn-start {
            background-color: #198754;
            color: white;
        }

        .btn-start:hover {
            background-color: #157347;
        }

        .alert {
            margin-top: 20px;
        }

        .fade-in {
            animation: fadeIn 0.5s ease-in-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            display: none;
        }

        .empty-state {
            text-align: center;
            padding: 50px 0;
            color: #6c757d;
        }
    </style>
<!--    输入框样式-->
    <style>
        .time-picker-container {
            max-width: 400px;
            margin: 50px auto;
            padding: 20px;
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .form-label {
            font-weight: 500;
            color: #2c3e50;
        }

        .time-input {
            position: relative;
        }

        .time-input input {
            padding-right: 40px;
            cursor: pointer;
        }

        .time-input .bi-clock {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 1.2rem;
            color: #3498db;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="card fade-in">
        <div class="card-header">
            <h4><i class="fa fa-graduation-cap mr-2"></i>考试成绩提交系统</h4>
        </div>
        <div class="card-body">
            <div class="text-center mb-4">
                <button id="fetch-subjects-btn" class="btn btn-primary btn-lg">
                    <i class="fa fa-download mr-2"></i>获取科目
                </button>
            </div>

            <div id="empty-state" class="empty-state">
                <i class="fa fa-book fa-5x mb-3 text-muted"></i>
                <p class="lead">点击上方"获取科目"按钮加载考试科目</p>
            </div>

            <div id="table-container" class="d-none">
                <table class="table table-striped table-bordered">
                    <thead>
                    <tr>
                        <th width="40%">考试科目</th>
                        <th width="15%">分数</th>
                        <th width="15%">次数</th>
                        <th width="15%">时间</th>
                        <th width="30%">操作</th>
                    </tr>
                    </thead>
                    <tbody id="exam-table-body">
                    <!-- 表格内容将通过 JavaScript 动态生成 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div id="result-alert" class="alert alert-success d-none fade-in">
        <strong>提交成功!</strong> 科目: <span id="subject-name"></span>, 分数: <span id="subject-score"></span>
    </div>

    <div id="error-alert" class="alert alert-danger d-none fade-in">
        <strong>操作失败!</strong> <span id="error-message"></span>
    </div>
</div>

<div class="loading-overlay" id="loading-overlay">
    <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">加载中...</span>
    </div>
</div>

<script>
    // 页面加载完成后初始化
    $(document).ready(function() {
        // 绑定获取科目按钮事件
        $("#fetch-subjects-btn").click(fetchExamSubjects);
    });

    // 从后端获取考试科目
    function fetchExamSubjects() {
        // 显示加载动画
        $("#loading-overlay").show();
        // 禁用按钮
        $("#fetch-subjects-btn").attr("disabled", true).html('<i class="fa fa-spinner fa-spin mr-2"></i>加载中...');

        $.ajax({
            url: "/base/getExamNameAll", // 替换为实际的API地址
            method: "GET",
            success: function(response) {
                // 隐藏加载动画
                $("#loading-overlay").hide();

                if (response && response.length > 0) {
                    // 成功获取科目数据
                    initExamTable(response);
                    // 显示表格，隐藏空状态
                    $("#table-container").removeClass("d-none");
                    $("#empty-state").addClass("d-none");
                    // 更改按钮文本
                    $("#fetch-subjects-btn").html('<i class="fa fa-refresh mr-2"></i>刷新科目');
                } else {
                    // 没有科目数据
                    showError("没有找到考试科目数据");
                    initExamTable(response);
                    // 恢复按钮状态
                    resetFetchButton();
                }
            },
            error: function(error) {
                // 隐藏加载动画
                $("#loading-overlay").hide();

                // 显示错误信息
                showError("获取考试科目失败: " + error.statusText);
                console.error("获取科目数据失败:", error);

                // 恢复按钮状态
                resetFetchButton();
            }
        });
    }

    // 重置获取按钮状态
    function resetFetchButton() {
        $("#fetch-subjects-btn").attr("disabled", false).html('<i class="fa fa-download mr-2"></i>获取科目');
    }

    // 显示错误提示
    function showError(message) {
        $("#error-message").text(message);
        $("#error-alert").removeClass("d-none");
        $("#error-alert").show();

        // 5秒后隐藏提示
        setTimeout(() => $("#error-alert").fadeOut(), 5000);
    }

    // 初始化考试表格
    function initExamTable(subjects) {
        const tableBody = $("#exam-table-body");
        tableBody.empty();
        // 为每个考试科目创建表格行
        subjects.forEach(subject => {
            const row = `
          <tr id="subject-row-${subject}">
            <td>${subject}</td>
            <td>
              <input type="number" class="form-control score-input mx-auto"
                     min="0" max="100" placeholder="分数"
                     data-subject-id="${subject}">
            </td>
            <td>
               <input type="number" class="form-control score-input mx-auto"
                     min="0" max="100" placeholder="次数"
                     data-subject-id="${subject}Number">
            </td>
             <td>
               <!-- 使用 HTML5 的 datetime-local 类型 -->
        <input type="datetime-local" class="form-control" data-subject-id="${subject}Time">
            </td>

            <td class="text-center">
              <button class="btn btn-primary btn-start"
                      data-subject-id="${subject}"
                      data-subject-name="${subject}">
                <i class="fa fa-play mr-1"></i> 开始
              </button>
            </td>
          </tr>
        `;
            tableBody.append(row);
        });

        // 绑定按钮点击事件
        bindButtonEvents();
    }
    function formatDateTime(isoDateTime) {
        if (isoDateTime==null) return null ;
        const date = new Date(isoDateTime);
        // 获取年、月、日、时、分
        const year = date.getFullYear();
        const month = date.getMonth() + 1; // 月份从0开始，所以+1
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = String(date.getMinutes()).padStart(2, '0'); // 确保分钟是两位数

        // 返回格式化后的字符串
        return `${year}/${month}/${day} ${hours}:${minutes}`;
    }
    // 绑定按钮事件
    function bindButtonEvents() {
        $(".btn-start").click(function() {
            const subjectId = $(this).data("subject-id");
            const subjectName = $(this).data("subject-name");
            const scoreInput = $(`input[data-subject-id="${subjectId}"]`);
            const number = $(`input[data-subject-id="${subjectId}Number"]`).val();
            const startTime =formatDateTime($(`input[data-subject-id="${subjectId}Time"]`).val()) ;
            const score = scoreInput.val();

            console.log(subjectName+score+startTime)
            // 验证分数
            if (!score || isNaN(score) || score < 0 || score > 100) {
                scoreInput.addClass("is-invalid");
                setTimeout(() => scoreInput.removeClass("is-invalid"), 2000);
                return;
            }

            // 提交数据到后台
            submitScore(subjectId, subjectName, score,number,startTime);
        });
    }

    // 提交分数到后台
    function submitScore(subjectId, subjectName, score,number,time) {
        // 显示加载状态
        const btn = $(`button[data-subject-id="${subjectId}"]`);
        btn.html('<i class="fa fa-spinner fa-spin mr-1"></i> 提交中...').attr("disabled", true);

        // 提交分数
        $.ajax({
            url: "/base/startExam", // 替换为实际的API地址
            method: "GET",
            data: {
                examName: subjectName,
                score: score,
                number:number,
                time:time
            },
            success: function(response) {
                // 显示成功提示
                $("#subject-name").text(subjectName);
                $("#subject-score").text(score);
                $("#result-alert").removeClass("d-none alert-danger").addClass("alert-success");
                $("#result-alert").show();
                // 重置按钮状态
                btn.html('<i class="fa fa-check mr-1"></i> 已提交').attr("disabled", true).addClass("btn-success");
                // 禁用输入框
                $(`input[data-subject-id="${subjectId}"]`).attr("disabled", true);
            },
            error: function(error) {
                // 显示错误提示
                $("#subject-name").text(subjectName);
                $("#subject-score").text(score);
                $("#result-alert").removeClass("d-none alert-success").addClass("alert-danger");
                $("#result-alert strong").text("提交失败!");
                $("#result-alert").show();

                // 重置按钮状态
                btn.html('<i class="fa fa-play mr-1"></i> 开始').attr("disabled", false);
            },
            complete: function() {
                // 5秒后隐藏提示
                setTimeout(() => $("#result-alert").fadeOut(), 5000);
            }
        });
    }
</script>


</body>
</html>